package com.code.google.mdsc.control.impl;

import java.io.File;

import javax.management.modelmbean.XMLParseException;
import javax.swing.JTable;

import com.code.google.mdsc.control.Business;
import com.code.google.mdsc.exception.BusinessException;
import com.code.google.mdsc.gui.MainWindow;
import com.code.google.mdsc.gui.listener.JProgressBarListener;
import com.code.google.mdsc.io.csv.impl.threading.CSVBookingParserTask;
import com.code.google.mdsc.io.log.SimpleLogger;
import com.code.google.mdsc.io.log.impl.SimpleLoggerImpl;
import com.code.google.mdsc.io.xml.impl.threading.XMLSepaGeneratorTask;
import com.code.google.mdsc.model.Creditor;

public class BusinessImpl implements Business {

	private static SimpleLogger logger = SimpleLoggerImpl.getInstance();
	private Creditor creditorData = null;

	@Override
	public void exit() {
		System.exit(0);
	}

	@Override
	public Creditor getCreditorData() {
		return creditorData;
	}

	@Override
	public void loadFromCSV(File selectedFile, MainWindow mw) {
		if (mw == null || selectedFile == null)
			throw new IllegalArgumentException("paramters must not be null");

		CSVBookingParserTask csvBookingParserTask = new CSVBookingParserTask(
				mw, this, selectedFile);

		csvBookingParserTask
				.addPropertyChangeListener(new JProgressBarListener(mw
						.getProgressBar()));
		csvBookingParserTask.execute();
	}

	@Override
	public void saveAsXML(File selectedFile, MainWindow mw) {
		if (mw == null || selectedFile == null)
			throw new IllegalArgumentException("paramters must not be null");

		XMLSepaGeneratorTask xmlSepaGeneratorTask;
		try {
			xmlSepaGeneratorTask = new XMLSepaGeneratorTask(selectedFile, mw,
					creditorData);
		} catch (XMLParseException e) {
			logger.log(SimpleLogger.LogMode.ERROR, e.getMessage());
			throw new BusinessException(e);
		}

		xmlSepaGeneratorTask
				.addPropertyChangeListener(new JProgressBarListener(mw
						.getProgressBar()));
		xmlSepaGeneratorTask.execute();
	}

	@Override
	public void search(MainWindow mw, String[] value) {

		if (mw == null || value == null)
			throw new IllegalArgumentException("paramters must not be null");

		JTable table = mw.getTable();

		for (int row = 0; row <= table.getRowCount() - 1; row++) {
			for (int val = 0; val < value.length; val++) {
				String currentValue = value[val];

				// magic line of code, change, if table column position changes
				int i = (val == 0) ? 1 : (val == 1) ? 5 : (val == 2) ? 6 : 0;

				String tableValue = (String) table.getValueAt(row, i);

				if (currentValue.equalsIgnoreCase(tableValue)) {

					mw.highlightSearchedValueInTable(row);
				}
			}
		}
	}

	@Override
	public void setCreditorData(Creditor creditorData) {
		if (creditorData == null)
			throw new IllegalArgumentException("paramters must not be null");

		this.creditorData = creditorData;

	}
}
